import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useAuthStore } from '@/store/auth';
import { RefundStatus } from '@/constants/orders';
import { getOrderPrerefundDetails } from '@/api/orders';

export const RouteMap = {
  home: '/pages/home/home',
  hotels: '/pages/hotels/list',
  hotelDetails: '/pages/hotels/details',
  hotelRoomAmenities: '/pages/hotels/room-amenities',
  checkout: '/pages/checkout/checkout',
  payment: '/pages/payment/payment',
  user: '/pages/user/user',
  joinUser: '/pages/user/join',
  account: '/pages/user/account',
  accountSet: '/pages/user/account-set',
  orders: '/pages/orders/list',
  orderDetails: '/pages/orders/details',
  orderRefundDetails: '/pages/orders/refund',
  trips: '/subpackages/trips/list',
  tripDetails: '/subpackages/trips/details',
  tripChangeProgress: '/subpackages/trips/change-progress',
  tripStayOn: '/subpackages/trips/stay-on',
  tripStayOnResult: '/subpackages/trips/stay-on-result',
  tripCard: '/subpackages/trips/card',
  login: '/pages/auth/login',
  countries: '/pages/auth/countries',
  webWeb: '/pages/web/web',
  webWebview: '/pages/web/webview',
  pointsList: '/pages/user/points',
  collectList: '/pages/user/collect',
  messageList: '/pages/user/message',
  userCancel: '/pages/user/cancel',
  userShare: '/pages/user/share',
  cs: '/pages/cs/cs',
  helpCenter: '/pages/help/index',
  helpCenterDetail: '/pages/help/detail',
  distributionIndex: '/pages/distribution/index',
  distributionOrder: '/pages/distribution/order',
  distributionOrderDetail: '/pages/distribution/order-detail',
  invite: '/pages/distribution/invite',
  withdraw: '/pages/distribution/withdraw',
  withdrawResult: '/pages/distribution/withdraw-result',
  withdrawList: '/pages/distribution/withdraw-list',
  withdrawDetail: '/pages/distribution/withdraw-detail',
  carIndex: '/pages/car/index',
  carHelp: '/pages/car/help',
  carList: '/pages/car/list',
  carCheckout: '/pages/car/submit',
  carOrderDetail: '/pages/car/order-detail',
  carOrderRefund: '/pages/car/order-refund',
  carTripDetail: '/pages/car/trip-detail',
  spaWait: '/pages/spa/wait',
  spaHome: '/subpackages/spa/pages/home',
  spaDetails: '/subpackages/spa/pages/details',
  spaBooking: '/subpackages/spa/pages/booking',
  spaCheckout: '/subpackages/spa/pages/checkout',
  spaOrderDetails: '/subpackages/spa/pages/order',
  spaOrderRefund: '/subpackages/spa/pages/refund',
  spaTrip: '/subpackages/spa/pages/trip',
  // restaurant: '/subpackages/restaurant-booking/pages/event-list',
  restaurant: '/subpackages/restaurant-booking/pages/home',
  restaurantList: '/subpackages/restaurant-booking/pages/restaurant-list',
  restaurantDetails: '/subpackages/restaurant-booking/pages/restaurant-details',
  restaurantBookingDetails: '/subpackages/restaurant-booking/pages/booking-details',
  restaurantBookingConfirmation: '/subpackages/restaurant-booking/pages/booking-confirmation',
  restaurantBookingCancellation: '/subpackages/restaurant-booking/pages/booking-cancellation',
  restaurantBookingTripDetails: '/subpackages/restaurant-booking/pages/trip-details',
  intentionIndex: '/pages/intention/index',
  couponList: '/pages/coupons/list',
  couponDetail: '/pages/coupons/details'
};

// 需要登录授权的路由
export const RequiredAuthRoutes: Array<(typeof RouteMap)[keyof typeof RouteMap]> = [
  RouteMap.cs,
  RouteMap.checkout,
  RouteMap.payment,
  RouteMap.account,
  RouteMap.orderDetails,
  RouteMap.orderRefundDetails,
  RouteMap.tripDetails,
  RouteMap.userCancel,
  RouteMap.userShare,
];

export const TabBarRoutes: Array<(typeof RouteMap)[keyof typeof RouteMap]> = [
  RouteMap.home,
  RouteMap.hotels,
  RouteMap.trips,
  RouteMap.user,
  RouteMap.cs
];

export const useRouter = defineStore('router', () => {
  const state = ref(RouteMap.home);
  const authStore = useAuthStore();

  function to(
    url: (typeof RouteMap)[keyof typeof RouteMap],
    params?: AnyObject,
    redirect?: boolean
  ) {
    if (TabBarRoutes.includes(url)) {
      state.value = url;
      return uni.redirectTo({
        url: mergeUrl(url, params)
      });
    }

    // 校验页面是否属于需要登录授权的页面
    // 如需要并且用户未登录，重定向至登录页
    if (RequiredAuthRoutes.includes(url) && !authStore.isLoggedIn) {
      return uni.redirectTo({
        url: RouteMap.login
      });
    }

    if (url === RouteMap.orderRefundDetails && params?.status !== RefundStatus.DONE) {
      getOrderPrerefundDetails(params!.orderSn).then((res) => {
        if (res.code === 0) {
          uni.navigateTo({
            url: mergeUrl(url, {
              ...params,
              data: JSON.stringify(res.data)
            })
          });
        }
      });
    } else if (redirect) {
      return uni.redirectTo({
        url: mergeUrl(url, params)
      });
    } else {
      uni.navigateTo({
        url: mergeUrl(url, params)
      });
    }
  }

  function back(delta: number = 1, success?: () => void) {
    uni.navigateBack({ delta, success });
  }

  function reLaunch(url: string) {
    uni.reLaunch({
      url
    });
  }

  return {
    state,
    to,
    back,
    reLaunch
  };
});

function mergeUrl(url: string, params?: AnyObject) {
  if (!params) return url;
  return `${url}?${Object.keys(params)
    .map((key) => `${key}=${params[key]}`)
    .join('&')}`;
}
